package com.erclab.xpresso.reports
{
	import com.erclab.xpresso.formelements.*;
	import com.erclab.xpresso.reports.filters.*;
	import com.erclab.xpresso.util.UIUtil;

	import mx.rpc.http.mxml.HTTPService;
	import flash.utils.*;
	import flash.display.DisplayObject;
	import mx.collections.ArrayCollection;
	import mx.core.UIComponent;

	public class FilterManager
	{
		
		protected var theFilters:ArrayCollection;
		protected var theReport:Report;
		
		public function FilterManager(theReport:Report):void{
			this.theReport = theReport;
		}
		
		protected function initElements():void{
			var dummy1:SimpleTextFilter = null;
		}
		
		public function applyFilter(item:Object):Boolean{
			var i:int = 0;
			for each ( var element:Filter in theFilters) {
				var columnValue:String = String(item[element.getColumnToFilter()]);
				var columnTofilter:String = element.getColumnToFilter();
				var theValue:String = element.getValue();
				if (columnValue.indexOf(theValue)){
					return true;
				}
			}
			return false;
		}
		
		public function createFilters(filterService:HTTPService, 
										attachingElement:UIComponent):void{
			
			if (attachingElement != null){
			
				var reportTitle:String = filterService.lastResult.report.title;
				var filters:ArrayCollection = filterService.lastResult.report.filterElement as ArrayCollection;
				theFilters = new ArrayCollection();
				
				theReport.theData.filterFunction = this.applyFilter;
	
				UIUtil.clearAttachingElement(attachingElement);
				for each ( var element:Object in filters) {
					
					initElements();
					
					var ClassReference:Class = getDefinitionByName(element.flexClass) as Class;
		            var instance:DisplayObject = new ClassReference();
		            var parameters:Object = element.parameters as Object;
					for (var p:String in element.parameters){
						instance[p] = element.parameters[p];
					}
					instance.name = element.columnToFilter;
					
		            theFilters.addItem(instance);
		            if (attachingElement != null) {
			            attachingElement.addChild(UIComponent(instance));
			            var f:Filter = Filter(instance);
			            f.setColumnToFilter(element.columnToFilter);
			            f.createLabel(attachingElement, element.label);
			            f.setReport(theReport);
		            }
				}
			}
		}
	
	}
}